﻿using System;
using System.ComponentModel;
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Esponce.QRCode;

namespace Esponce.Models
{
	public class MainViewModel : INotifyPropertyChanged
	{
		#region Constructor
		public MainViewModel()
		{
			this.Content = "Hello World!";
		}
		#endregion

		#region Public properties
		public string Content
		{
			get
			{
				return this.content;
			}
			set
			{
				if (this.content != value)
				{
					this.content = value;
					OnPropertyChanged("Content");
				}
			}
		}
		private string content;

		public ImageSource Image
		{
			get
			{
				return this.image;
			}
			set
			{
				if (this.image != value)
				{
					this.image = value;
					OnPropertyChanged("Image");
				}
			}
		}
		private ImageSource image;

		public bool IsLoading
		{
			get
			{
				return this.isLoading;
			}
			set
			{
				if (this.isLoading != value)
				{
					this.isLoading = value;
					OnPropertyChanged("IsLoading");
				}
			}
		}
		private bool isLoading;
		#endregion

		#region Public methods
		public void GenerateDirectly()
		{
			//Prepare data for QR Code
			var model = new QRCodeModel() { Content = this.Content };

			//Build URL
			var client = CreateClient();
			var url = client.UriBuilder.BuildGenerateUrl(model);

			//Load image
			this.Image = new BitmapImage(new Uri(url, UriKind.Absolute));
		}

		public void Generate()
		{
			try
			{
				//Start the loading animation for better UX
				this.IsLoading = true;

				var client = CreateClient();
				client.GenerateCompleted += (sender, e) =>
				{
					//Read stream now because it cannot be transfered to UI thread
					byte[] data = null;
					if (e.Stream != null)
					{
						byte[] buffer = new byte[e.ContentLength];
						e.Stream.Read(buffer, 0, buffer.Length);
						data = buffer;
					}

					//Go back to UI thread
					Deployment.Current.Dispatcher.BeginInvoke(() =>
					{
						//Stop the loading animation
						this.IsLoading = false;

						if (e.Error == null)
						{
							var im = new BitmapImage();
							im.SetSource(new MemoryStream(data));
							this.Image = im;
						}
						else
						{
							//Report error to the console
							MessageBox.Show(e.Error.Message + Environment.NewLine + e.Error.StackTrace, "Error", MessageBoxButton.OK);
						}
					});
				};
				client.GenerateAsync(this.Content);
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK);
			}
		}

		public QRCodeClient CreateClient()
		{
			var client = new QRCodeClient();
			client.UseSSL = false;
			client.ApiKey = null;
			client.Format = ApiFormat.Json;
			client.ApplicationName = "EsponceAPIDemo/1.0 (Silverlight)";
			return client;
		}
		#endregion

		#region INotifyPropertyChanged Members
		public event PropertyChangedEventHandler PropertyChanged;
		protected virtual void OnPropertyChanged(string propertyName)
		{
			if (PropertyChanged != null)
			{
				PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
			}
		}
		#endregion
	}
}
